package org.jaaksi.kottlindemo.home

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import extension.FragmentWrapper
import extension.addFragments
import extension.showFragment
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import libcore.eventbus2.EventBus
import libcore.util.ImmersiveUtil
import org.jaaksi.kottlindemo.R
import org.jaaksi.kottlindemo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val homeViewModel by viewModels<HomeViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ImmersiveUtil.setStatusBarTranslucent(window)
        ImmersiveUtil.setStatusBarDarkMode(window)
        setContentView(binding.root)

        lifecycleScope.launch {
            homeViewModel.changeTabFlow.collect {
                binding.navView.selectedItemId = it
            }
        }


        binding.navView.setOnNavigationItemSelectedListener {
            showFragment(
                supportFragmentManager, R.id.flContainer,
                when (it.itemId) {
                    R.id.navigation_calculate -> CalculatorFragment::class.java
                    R.id.navigation_history -> HistoryFragment::class.java
                    else -> StatisticsFragment::class.java
                }
            )

            return@setOnNavigationItemSelectedListener true
        }
        addFragments(
            supportFragmentManager, R.id.flContainer,
            FragmentWrapper(
                CalculatorFragment::class.java,
                isHide = false
            ),
            FragmentWrapper(HistoryFragment::class.java),
            FragmentWrapper(StatisticsFragment::class.java)
        )

//        supportFragmentManager.setFragmentResultListener("toast", this) { requestKey, result ->
//            println(">> MainActivity result = $result")
//        }

    }

    override fun onBackPressed() {
        super.onBackPressed()
        EventBus.clear()
    }
}